<?php

namespace app\controller;

use app\BaseController;
use app\controller\model\Config;
use app\controller\model\SPay;
use think\facade\Session;
use think\facade\Db;

class Notify extends BaseController
{
	public function __construct()
	{
	}

	public function index()
	{
		//支付订单异步通知
		$json = request()->param();
		if (isset($json['resultCode']) && $json['resultCode'] == 'SUCCESS' && $json['status'] == 'PAY_SUCCESS') {
			$this->setSuccess($json);
		}
		echo "SUCCESS";
		exit();
	}
	public function setSuccess($json){
		$payModel = new model\SPay();
		$out_trade_no = $json['outTradeNo'];
		$order = $payModel->queryOrder($out_trade_no);
		if (isset($order['resultCode']) && $order['resultCode'] == 'SUCCESS' && $order['status'] == 'PAY_SUCCESS') {
			Db::startTrans();
			try {
				$re = DB::name("orders")->lock(true)->where("order_no", $out_trade_no)->where("status", 2)->find();
				if ($re && $re['status']==2) {
					$user = rusers($re['uid']);
					$up = DB::name("orders")->where("order_no", $out_trade_no)->update(['status' => 4, 'payTime' => date("Y-m-d H:i:s"),'payJson'=>$order['payerInfo']]);
					//设置完成
					if ($up) {
						DB::name("users")->where("id",$re['uid'])->update([
							'amount'=>bcadd($user['amount'],$re['amount'],2),
							'volume'=>bcadd($user['volume'],$re['volume'],2),
							'subPrice'=>bcadd($user['subPrice'],$re['sale'],2),
							'payPrice'=>bcadd($user['payPrice'],$re['payPrice'],2),
						]);
						//处理上游订单
						$supplierModel = new model\Supplier($re['supplierID']);
						$supplierOrder = $supplierModel->mkOrder($re);
						if($supplierOrder === true){
							$re = DB::name("orders")->where("id", $re['id'])->find();
							$supplierModel->confirmOrder($re);
						}
					}
				}
				Db::commit();
			} catch (Exception $e) {
				$file = fopen("./t_notify_err2.txt", "w");
				fwrite($file, $e);
				fclose($file);
				Db::rollback();
			}
		}
	}
	//{"timeEnd":"20250606180357","mchId":"44507663","chargeInfo":"{\"feeAmount\":\"0\",\"payMoney\":\"1\",\"invoiceAmount\":\"1\",\"settlementTotalFee\":\"1\"}","resultCode":"SUCCESS","sign":"oFJRa81ZeRKtJz0Z37XweFx751hd3oy5x8FnGE1R+uVft8\/o16ljl8mvIdDb\/hUeC2VLf\/yHr5csx4D0NLSFe1TRREpaauMlY5v\/uqhz5\/tMgikxNo2i2l7dUGcdPEAW5gXAx4H3gXxWG25IIfF99uKjWumr6vffT335MK+7Ay4=","nonceStr":"giLoicxkxqskfhOYkJfiCgcNLpSTNqHH","transactionId":"M202506061137808272243023872","returnCode":"SUCCESS","returnMsg":"SUCCESS","payerInfo":"{\"bankType\":\"OTHERS\",\"openid\":\"oiFTg4oZ2ea8PFZUwZAfRRtfe3qw\",\"subOpenid\":\"onaIA7v8biHQ_b_K28rpxW6Dloys\",\"officOrderNum\":\"4200002701202506061232535819\",\"userid\":\"onaIA7v8biHQ_b_K28rpxW6Dloys\",\"transactionId\":\"801025060698736051\"}","totalFee":1,"outTradeNo":"JZX20250606180351174920423145435","signType":"RSA","attach":"{\"officOrderNum\":\"4200002701202506061232535819\",\"body\":\"\u5e7f\u805a\u80fd\u6e90\u4e8c\u7ad91\u52a0\u6cb9\",\"sftInstOrderNo\":\"801025060698736051\"}","tradeType":"wx_lite","status":"PAY_SUCCESS"}
}
